<template>
    <div class="marketing_conpon">
        <div class="zw-form-layout">
            <el-form ref="formRef" :model="form" label-width="auto">
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="优惠券名称" prop="couponName">
                            <el-input v-model="form.couponName" clearable placeholder="请输入优惠券名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="优惠券状态" prop="couponStatus">
                            <el-select v-model="form.couponStatus" clearable placeholder="请选择状态">
                                <el-option
                                    v-for="item in couponStatusList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="优惠券类型" prop="couponType">
                            <el-select v-model="form.couponType" clearable placeholder="请选择类型">
                                <el-option
                                    v-for="item in couponTypeList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" class="zw-form-btns">
                        <el-button type="primary" @click="searchHandler">查询</el-button>
                        <el-button plain @click="resetHandler">清空</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <el-row>
            <el-col class="zw-table-btns">
                <el-button type="primary" v-auth="'coupon_list:creat'" @click="showDialogHanlder('', '')">
                    新建
                </el-button>
            </el-col>
        </el-row>
        <el-table :data="tableList" stripe>
            <el-table-column label="优惠券名称" prop="couponName"></el-table-column>
            <el-table-column label="类型" prop="couponType">
                <template v-slot="{ row }">
                    {{ row.couponType === 1 ? '满减券' : '折扣券' }}
                </template>
            </el-table-column>
            <el-table-column label="优惠内容" min-width="100" prop="couponDiscountContent">
                <template v-slot="{ row }">
                    {{ couponContent(row) }}
                </template>
            </el-table-column>
            <!-- 1 未开始  2 进行中 3 失效  4 已结束 -->
            <el-table-column label="状态" prop="couponStatus">
                <template v-slot="{ row }">
                    {{ (row.couponInfo || [])[0]?.couponStatusName }}
                </template>
            </el-table-column>
            <el-table-column label="已领取/剩余" min-width="90" prop="couponAcquiredNumber">
                <template v-slot="{ row }">
                    {{ row.couponAcquiredNumber }}/{{
                        (row.couponInfo || [])[0]?.couponTotal - row.couponAcquiredNumber
                    }}
                </template>
            </el-table-column>
            <el-table-column label="已使用" prop="couponUsedNumber"></el-table-column>
            <el-table-column label="支付金额(元)" min-width="90" prop="couponPaidNumber">
                <template v-slot="{ row }">
                    {{ floatDivide(row.couponPaidNumber, 100) }}
                </template>
            </el-table-column>
            <el-table-column label="客单价(元)" prop="couponPerCustomerPrice">
                <template v-slot="{ row }">
                    {{ floatDivide(row.couponPerCustomerPrice, 100) }}
                </template></el-table-column
            >
            <el-table-column fixed="right" label="操作" width="270">
                <template v-slot="{ row }">
                    <!-- 优惠券失效及被领取后 不可以再编辑  -->
                    <div class="btns">
                        <el-button size="small" @click="showDialogHanlder(row.id, 1)"> 详情 </el-button>
                        <el-button
                            size="small"
                            v-auth="'coupon_list:edit'"
                            v-show="(row.couponInfo || [])[0]?.couponStatus !== 3 && row.couponAcquiredNumber <= 0"
                            @click="showDialogHanlder(row.id)">
                            编辑
                        </el-button>
                        <!-- 已过期不能失效 -->
                        <el-button
                            size="small"
                            v-auth="'coupon_list:invalid'"
                            v-show="[1, 2].includes((row.couponInfo || [])[0]?.couponStatus)"
                            @click="invalidHandler(row)">
                            失效
                        </el-button>
                        <el-button size="small" v-auth="'coupon_list:copy'" @click="getLinkHandler(row)">
                            复制链接
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <div style="margin-top: 15px">
            <Pagination
                :total="totalCount"
                :page-size="form.perPage"
                :current-page="form.page"
                @sizeChange="changeSizeHandler"
                @pageChange="changePageHandler" />
        </div>
        <el-drawer size="45%" v-model="dialogVisible" :title="title" :with-header="true">
            <Detail
                ref="DetailRef"
                v-if="dialogVisible"
                @closeDialog="closeDialogHandler"
                :couponId="couponId"></Detail>
            <template #footer>
                <el-button @click="closeDialogHandler">取消</el-button>
                <el-button type="primary" v-show="!dialogReadonly" @click="submitHandler"> 确认 </el-button>
            </template>
        </el-drawer>
    </div>
</template>

<script setup name="merberList">
import { ref, reactive, onMounted, onActivated, computed } from 'vue';
import Pagination from '@/components/Pagination.vue';
import request from '@/request/index';
import constants from '@/commons/constants';
import { packSelectObjUtil, floatDivide } from '@/commons/utils';
import Detail from './detail.vue';
import ElemBox from '@/commons/element/message.js';
import { ElMessage } from 'element-plus';

const couponStatusList = reactive(packSelectObjUtil(constants.COUPON_STATUS_OPTIONS));
const couponTypeList = reactive(packSelectObjUtil(constants.COUPON_TYPE_OPTIONS));
const totalCount = ref(0);
const form = reactive({
    page: 1,
    perPage: 10,
    couponName: null,
    couponStatus: null,
    couponType: null
});
let tableList = reactive([]);
let dialogVisible = ref(false);
let dialogReadonly = ref(false);
let couponId = ref('');
const formRef = ref(null);

const title = computed(() => {
    if (couponId.value) {
        return dialogReadonly.value ? '优惠券详情' : '编辑优惠券';
    }
    return '新建优惠券';
});
/**
 * 分页查询
 */
const queryCouponListHandler = async () => {
    const res = await request('couponListServ', form);
    const list = res.data.list || [];
    tableList.length = 0;
    tableList.push(...list);
    totalCount.value = res.data.totalCount;
};

/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    queryCouponListHandler();
};

const invalidHandler = row => {
    ElemBox.ElMessageBoxPromise(`确定要失效该优惠券？`)
        .then(res => {
            request('couponExpireServ', { id: row.id, couponStatus: 3 }).then(res => {
                ElMessage.success(`操作成功`);
                searchHandler();
            });
        })
        .catch(() => {});
};
const getLinkHandler = row => {
    request('couponShareServ', { id: row.id }).then(res => {
        const url = res.data;
        const inputDom = document.createElement('input');
        inputDom.value = url;
        document.body.appendChild(inputDom);
        inputDom.select();
        document.execCommand('Copy');
        inputDom.remove();
        ElMessage.success(`已复制到粘贴板`);
    });
};

/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    queryCouponListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.perPage = perPage;
    queryCouponListHandler();
};

const showDialogHanlder = (id, type) => {
    dialogReadonly.value = !!type;
    couponId.value = id || '';
    dialogVisible.value = true;
};

/**
 * 关闭弹窗
 */
const closeDialogHandler = val => {
    dialogVisible.value = false;
    if (val) {
        queryCouponListHandler();
    }
};
const DetailRef = ref(null);
const submitHandler = () => {
    DetailRef.value.submitHandler();
};
const couponContent = row => {
    const obj = (row?.couponInfo || [])[0] || {};
    let pre = '';
    let num = '';
    switch (obj.couponPrerequisites) {
        case 1:
            pre = '无门槛';
            break;
        case 2:
            pre = `满${floatDivide(obj.couponPrerequisitesAdditional, 100)}`;
            break;
        case 3:
            pre = `满${obj.couponPrerequisitesAdditional}件`;
            break;
        default:
            break;
    }
    switch (obj.couponType) {
        case 1:
            num = `减${floatDivide(obj.couponDiscountContent, 100)}`;
            break;
        case 2:
            num = `打${floatDivide(obj.couponDiscountContent, 100)}折`;
            break;
        default:
            break;
    }
    return pre + num;
};

onMounted(() => {
    searchHandler();
});
</script>

<style lang="scss" scoped>
.marketing_conpon {
    .btns {
        display: flex;
        flex-wrap: wrap;
        .el-button + .el-button {
            margin-left: 0;
        }
        .el-button {
            margin-bottom: 6px;
            margin-right: 6px;
        }
    }
}
</style>
